//
//  WBTaBar.swift
//  SainMicroblog
//
//  Created by chenxinju on 16/5/3.
//  Copyright © 2016年 chenxinju-a2. All rights reserved.
//

import UIKit

class WBTaBar: UITabBar {
    
    //1.定义一个闭包属性
    var closure: (()->())?
    
    //代码自定义视图
    override  init(frame: CGRect) {
        super.init(frame: frame)
        //添加Button
        self .setupUI()
    }
    
    
    //当通过StoryBoard来加载视图的会调用此方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //此方法 用来添加子控件的约束---private私有方法
    private func setupUI() {
        addSubview(compose2Button)
    }
    
    
    
    //按钮的点击方法 并调用闭包
    func showPubhish() {
        closure?() //系统会进行强制解包
    }
    
    //-----------------------中间+号按钮布局设置----------------
    override func layoutSubviews() {
        //调用父类的
        super.layoutSubviews()
        //定义一个索引
        var index: CGFloat = 0
        //设置按钮的宽度
        let width = bounds.width / 5.0
        //遍历拿到子控件
        for subview in subviews {
            //输出可选项
            //printLog(subview)
            //将字符串转换为类名
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!){
                //printLog("这是要移动位置的")
                subview.frame = CGRectMake(index*width, 0, width, bounds.height)
                //值改变
                index += 1
                
                if index == 2{ //如果右边向右移动
                    index += 1
                }
            }
        }
        //修改一下button 的位置
        compose2Button.frame = CGRectMake(width*2, 0, width, bounds.height)
    }
    
    
    
    
    //懒加载第一种写法
    //let compose2Button = UIButton(type: UIButtonType.Custom)
    //2.栏加载第二种写法: 懒加载相当于闭包 可在其中设置属性
    lazy var compose2Button: UIButton = {
        let button = UIButton(type: UIButtonType.Custom)
        
        //设置默认状态
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        //选择状态
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //默认状态图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        //让按钮自适应
        button.sizeToFit()
        
        //给按钮添加点击事件
        button.addTarget(self, action: "showPubhish", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}
